<?php


namespace App\Biquge;


use App\Utils\HtmlDom;

class Character
{

    protected $host = 'http://www.biqukan.com';

    protected $path = 'books';

    public function crawl($character, $book_id)
    {
        $path = $this->getPath($book_id, $character['title']);
        if (!file_exists($path)) {
            $response = ioc('request')->request('get', $this->host.$character['url']);
            $content = $response->getBody()->getContents();
            if ($content) {
                $query = new HtmlDom($content);
                $title = $query->query(".//div[contains(@class,'content')]//h1")
                    ->item(0)->textContent;
                $content = $query->query('.//div[@id="content"]')->item(0)->textContent;
                $content = preg_replace('/\((http|https).*biqu.*/', '', $content);
                file_put_contents($this->getPath($book_id, $title), $content);
                unset($query, $content);
            }
        }
    }

    protected function getPath($id, $title)
    {
        $path = $this->path . '/' . $id;
        $this->makeDir([$this->path, $id]);
        return $path . '/' . $title . '.txt';
    }


    protected function makeDir(array $dirs)
    {
        $prefix = null;
        foreach ($dirs as $key=>$dir) {
            if ($key == 0) {
                $prefix = '.';
            }
            $prefix = $prefix.'/'.$dir;
            if (!is_dir($prefix)) {
                @mkdir($prefix);
            }
        }
    }
}